﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LHS.Core.TableInfo;
using MS.Core.Constants.Objects;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using MS.Core.Base.Transaction;

namespace LHS.Win
{
    public partial class frmCTPhauThuat : Form
    {
        #region Variable
        LHS.Core.Clinical.ClinicalController objController = new LHS.Core.Clinical.ClinicalController();
        // Methods
        private string _strCLRISN = string.Empty;
        private string _strPATISN = string.Empty;
        private DataTable _dtEmployee = null;
        private bool _blnInsert = false;
        private string _strPatID = string.Empty;
        private int _intLanKham = 0;
        private int _intLanTaiKham = 0;
        private string _strPhauThuat = string.Empty;
        private DataTable _dtSurgical;
        private Boolean _refreshLoadImage = false; // false: chua refresh image, true: da refresh image roi
        private DateTime _dteNgayKham;
        private string strSuffix = string.Empty;
        private int isn = 0;
        #endregion

        #region Constructor
        public frmCTPhauThuat(string strPatISN, string strPatID, string strCLRISN, DataTable dtEmployee, bool blnInsert, string strLanKham, string strLanTaiKham, string strPhauThuat, DateTime dteNgayKham)
        {
            InitializeComponent();
            _strCLRISN = strCLRISN;
            _strPATISN = strPatISN;
            _strPatID = strPatID;
            _dtEmployee = dtEmployee.Copy();
            _intLanKham = string.IsNullOrEmpty(strLanKham) == true ? 0 : Convert.ToInt32(strLanKham);
            _intLanTaiKham = string.IsNullOrEmpty(strLanTaiKham) == true ? 0 : Convert.ToInt32(strLanTaiKham);
            _strPhauThuat = strPhauThuat;
            _blnInsert = blnInsert;
            _dteNgayKham = dteNgayKham;
        }
        #endregion

        private void frmCTPhauThuat_Load(object sender, EventArgs e)
        {
            LoadCboData();
            #region Load thong tin tab 1
            //load cac du lieu mac dinh
            dtpNgaygioPT.Value = DateTime.Now;

            if (_blnInsert == false) //cập nhật --> cần phải load thông tin liên quan chi tiết phẫu thuật
            {
                List<ExpressionObject> param = new List<ExpressionObject>();
                param.Add(new ExpressionObject(InfoSurgeryDetail.CLRISN, _strCLRISN));
                DataTable dtSurgeryDetail = objController.GetData(InfoSurgeryDetail.TABLENAME, param);
                if (dtSurgeryDetail != null && dtSurgeryDetail.Rows.Count > 0)
                {
                    try
                    {
                        DataRow drSurgeryDetail = dtSurgeryDetail.Rows[0];
                        txtPPPT.Text = drSurgeryDetail[InfoSurgeryDetail.SURSURGERYMETHOD].ToString();
                        cbBacSiPT.SelectedValue = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURDOCTORPRIMARY].ToString()) ? "-1" : drSurgeryDetail[InfoSurgeryDetail.SURDOCTORPRIMARY].ToString();
                        cbBSPhu1.SelectedValue = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR1].ToString()) ? "-1" : drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR1].ToString();
                        cbBSPhu2.SelectedValue = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR2].ToString()) ? "-1" : drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR2].ToString();
                        cbBSPhu3.SelectedValue = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR3].ToString()) ? "-1" : drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR3].ToString();
                        cbBSGayMe.SelectedValue = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURDOCTORANAESTHETIZE].ToString()) ? "-1" : drSurgeryDetail[InfoSurgeryDetail.SURDOCTORANAESTHETIZE].ToString();
                        cbDieuDuong.SelectedValue = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURTREATHELPER].ToString()) ? "-1" : drSurgeryDetail[InfoSurgeryDetail.SURTREATHELPER].ToString();
                        txtTuongTrinhPhauThuat.Text = drSurgeryDetail[InfoSurgeryDetail.SURSURGERYREPORT].ToString();
                        dtpNgaygioPT.Value = string.IsNullOrEmpty(drSurgeryDetail[InfoSurgeryDetail.SURSURGERYDATE].ToString()) ? DateTime.Now : DateTime.Parse(drSurgeryDetail[InfoSurgeryDetail.SURSURGERYDATE].ToString());
                    }
                    catch (Exception ex)
                    {
                        Class.ShowException(ex);
                    }
                }
            }
            else
            {
                cbBacSiPT.SelectedIndex = 0;
                cbBSPhu1.SelectedIndex = 0;
                cbBSPhu2.SelectedIndex = 0;
                cbBSPhu3.SelectedIndex = 0;
                cbBSGayMe.SelectedIndex = 0;
                cbDieuDuong.SelectedIndex = 0;
            }
            #endregion

        }

        /// <summary>
        /// load toan bộ dữ liệu liên quan dến combobox
        /// </summary>
        private void LoadCboData()
        {
            try
            {
                DataRow dr = _dtEmployee.NewRow();
                dr[InfoEmployees.EMPNAME] = "";
                dr[InfoEmployees.EMPISN] = -1;
                _dtEmployee.Rows.InsertAt(dr, 0);

                cbBacSiPT.DataSource = _dtEmployee;
                cbBacSiPT.DisplayMember = InfoEmployees.EMPNAME;
                cbBacSiPT.ValueMember = InfoEmployees.EMPISN;

                cbBSPhu1.DataSource = _dtEmployee.Copy();
                cbBSPhu1.DisplayMember = InfoEmployees.EMPNAME;
                cbBSPhu1.ValueMember = InfoEmployees.EMPISN;

                cbBSPhu2.DataSource = _dtEmployee.Copy();
                cbBSPhu2.DisplayMember = InfoEmployees.EMPNAME;
                cbBSPhu2.ValueMember = InfoEmployees.EMPISN;

                cbBSPhu3.DataSource = _dtEmployee.Copy();
                cbBSPhu3.DisplayMember = InfoEmployees.EMPNAME;
                cbBSPhu3.ValueMember = InfoEmployees.EMPISN;

                cbBSGayMe.DataSource = _dtEmployee.Copy();
                cbBSGayMe.DisplayMember = InfoEmployees.EMPNAME;
                cbBSGayMe.ValueMember = InfoEmployees.EMPISN;

                cbDieuDuong.DataSource = _dtEmployee.Copy();
                cbDieuDuong.DisplayMember = InfoEmployees.EMPNAME;
                cbDieuDuong.ValueMember = InfoEmployees.EMPISN;

                if (string.IsNullOrEmpty(_strPhauThuat.Trim()) == false)
                {
                    _strPhauThuat = _strPhauThuat.Trim().Replace("\r\n-", ";");
                    _dtSurgical = objController.getSurgical(_strPhauThuat);
                    if (_dtSurgical != null && _dtSurgical.Rows.Count > 0)
                    {
                        foreach (DataRow drSurgical in _dtSurgical.Rows)
                        {
                            if (string.IsNullOrEmpty(drSurgical[InfoSurgical.SURSYMBOL].ToString()))
                            {
                                MessageBox.Show("Bạn vui lòng nhập đầy đủ chữ viết tắt cho phẫu thuật", "Thông Báo");
                                base.Close();
                            }
                        }

                        cboLoaiPhauThuat.DataSource = _dtSurgical;
                        cboLoaiPhauThuat.DisplayMember = InfoSurgical.SURNAME;
                        cboLoaiPhauThuat.ValueMember = InfoSurgical.SURISN;
                        cboLoaiPhauThuat.SelectedIndex = 0;
                    }
                    cboLoaiPT_HA.Properties.DataSource = _dtSurgical.Copy();
                    cboLoaiPT_HA.Properties.DisplayMember = InfoSurgical.SURNAME;
                    cboLoaiPT_HA.Properties.ValueMember = InfoSurgical.SURISN;
                    cboLoaiPT_HA.ItemIndex = 0;
                }
                else
                {
                    cboLoaiPhauThuat.DataSource = null;
                    cboLoaiPT_HA.Properties.DataSource = null;
                }
            }
            catch
            {

            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (checkData() == false)
                return;

            DataTable dtSurgeryDetail = InfoSurgeryDetail.GetStructure();
            dtSurgeryDetail.Columns.Remove(InfoSurgeryDetail.SURISN);
            DataRow drSurgeryDetail = dtSurgeryDetail.NewRow();
            drSurgeryDetail[InfoSurgeryDetail.CLRISN] = _strCLRISN;
            drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR1] = cbBSPhu1.SelectedIndex == -1 ? DBNull.Value : cbBSPhu1.SelectedValue;
            drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR2] = cbBSPhu2.SelectedIndex == -1 ? DBNull.Value : cbBSPhu2.SelectedValue;
            drSurgeryDetail[InfoSurgeryDetail.SURDOCTOR3] = cbBSPhu3.SelectedIndex == -1 ? DBNull.Value : cbBSPhu3.SelectedValue;
            drSurgeryDetail[InfoSurgeryDetail.SURDOCTORANAESTHETIZE] = cbBSGayMe.SelectedIndex == -1 ? DBNull.Value : cbBSGayMe.SelectedValue;
            drSurgeryDetail[InfoSurgeryDetail.SURDOCTORPRIMARY] = cbBacSiPT.SelectedIndex == -1 ? DBNull.Value : cbBacSiPT.SelectedValue;
            drSurgeryDetail[InfoSurgeryDetail.SURSURGERYDATE] = dtpNgaygioPT.Value;
            drSurgeryDetail[InfoSurgeryDetail.SURSURGERYMETHOD] = txtPPPT.Text;
            drSurgeryDetail[InfoSurgeryDetail.SURSURGERYREPORT] = txtTuongTrinhPhauThuat.Text;
            drSurgeryDetail[InfoSurgeryDetail.SURTREATHELPER] = cbDieuDuong.SelectedIndex == -1 ? DBNull.Value : cbDieuDuong.SelectedValue;

            dtSurgeryDetail.Rows.Add(drSurgeryDetail);

            if (_blnInsert == true)
            {
                //insert
                try
                {
                    objController.InsertRow(drSurgeryDetail, new string[] { InfoSurgeryDetail.SURISN });
                    _blnInsert = false;
                    MessageBox.Show("Đã thêm mới thành công", "Thông Báo", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    Class.ShowException(ex);
                }
            }
            else
            {
                //update
                try
                {
                    List<ExpressionObject> param = new List<ExpressionObject>();
                    param.Add(new ExpressionObject(InfoClinicalRecord.CLRISN, _strCLRISN));

                    objController.UpdateRow(drSurgeryDetail, param);
                    MessageBox.Show("Đã cập nhật thành công", "Thông Báo", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    Class.ShowException(ex);
                }
            }
        }

        private bool checkData()
        {
            if (cbBacSiPT.SelectedIndex == 0)
            {
                MessageBox.Show("Vui lòng chọn bác sỹ phẫu thuật", "Thông Báo", MessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            GC.Collect();
            base.Close();
        }

        #region Tab Changed
        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (e.Page.Name == this.tabHinhAnh.Name)
            {
                //get max index.
                isn = objController.GetNewCLRPIC(_strCLRISN);
                if (gdHinhAnh.DataSource == null && _refreshLoadImage == false)
                {
                    //lay ra ngay chenh lech giua lan kham hien tai va lan kham truoc do (lan tai kham)
                    strSuffix = "_" + objController.getSuffixFromExaminationDate(_strPatID, _intLanKham, _intLanTaiKham, _dteNgayKham);

                    // neu grid hinh anh bang null, nghia la chua lay du lieu lan nao, neu lay roi thi khong lay nua
                    ///lay du lieu duoi DB len.
                    ///sau do save hinh anh tu server ve local
                    ///tu do load du lieu duoi local len sai
                    DataTable _dtHinhAnh = objController.getPicture(_strPatID);
                    if (_dtHinhAnh != null && _dtHinhAnh.Rows.Count > 0)
                    {
                        _dtHinhAnh.Columns.Add(InfoClinicalPicture.HIDDEN_STATUS, typeof(int));
                        _dtHinhAnh.Columns.Add(InfoClinicalPicture.HIDDEN_IMAGE, typeof(Bitmap));
                        _dtHinhAnh.Columns.Add(InfoClinicalPicture.HIDDEN_PICNAME, typeof(string));
                        _dtHinhAnh.Columns.Add(InfoClinicalPicture.HIDDEN_PICPATH, typeof(string));
                        _dtHinhAnh.Columns.Add(InfoClinicalPicture.HIDDEN_CHECK, typeof(int));
                        string strServerPath = string.Empty;
                        string strLocalPath = string.Empty;
                        Bitmap img;

                        foreach (DataRow dr in _dtHinhAnh.Rows)
                        {
                            strServerPath = System.Configuration.ConfigurationManager.AppSettings["ServerImagePath"].ToString();
                            strLocalPath = System.Configuration.ConfigurationManager.AppSettings["LocalImagePath"].ToString();
                            strServerPath = strServerPath + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICTURE].ToString() + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICNAME].ToString();

                            if (File.Exists(strServerPath))
                            {
                                if (Directory.Exists(strLocalPath) == false) //neu thu  muc khong ton tai
                                {
                                    Directory.CreateDirectory(strLocalPath);
                                }
                                strLocalPath = strLocalPath + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICNAME].ToString();

                                if (File.Exists(strLocalPath) == false)
                                {
                                    File.Copy(strServerPath, strLocalPath);
                                   
                                }
                                img = new Bitmap(strLocalPath);
                                dr[InfoClinicalPicture.HIDDEN_IMAGE] = img; //lay hinh tu may local len xem
                            }

                            dr[InfoClinicalPicture.HIDDEN_PICPATH] = dr[InfoClinicalPicture.CLPPICTURE]; // luu giu file cu truoc khi update, vi neu co update, phai xoa file cu tren duong dan vat ly
                            dr[InfoClinicalPicture.HIDDEN_PICNAME] = dr[InfoClinicalPicture.CLPPICNAME];
                            dr[InfoClinicalPicture.HIDDEN_STATUS] = (int)InfoClinicalPicture.eHiddenStatus._HaveValue;
                            dr[InfoClinicalPicture.HIDDEN_CHECK] = 0;
                        }
                    }
                    else
                    {
                        _dtHinhAnh = InfoClinicalPicture.GetStructure();
                    }
                    gdHinhAnh.DataSource = _dtHinhAnh;
                    gvHinhAnh.ExpandAllGroups();
                }
            }
            else if (e.Page.Name == this.tabThongTinChiTiet.Name)
            {
                if (cboLoaiPhauThuat.DataSource != null)
                {
                    cboLoaiPhauThuat_SelectedIndexChanged(sender, e);
                }
            }
        }
        #endregion

        #region Hinh Anh
        private void gdHinhAnh_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            if (gdHinhAnh.DataSource == null)
            {
                e.Handled = true;
                return;
            }
            if (cboLoaiPT_HA.ItemIndex == -1)
            {
                cboLoaiPT_HA.ItemIndex = 0;
            }
            if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Append)
            {
                e.Handled = true;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = true; // cho chon mot luc nhieu file
                dialog.Filter = "JPEG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif|Bitmap Files (*.bmp)|*.bmp";
                dialog.FilterIndex = 1;
                dialog.RestoreDirectory = true;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    DataTable dt = (DataTable)gdHinhAnh.DataSource;
                    DataRow dr = null;
                    foreach (string filename in dialog.FileNames)
                    {
                        dr = dt.NewRow();

                        dr[InfoClinicalPicture.CLPISN] = isn;
                        dr[InfoClinicalPicture.CLPNO] = isn;
                        isn++;
                        //duong dan hien tai bao gom : ten thu muc : ten tắt của phẫu thuật + id theo thứ tự (có bước nhảy) ;
                        //kiem tra so id co thuoc buoc nhay, neu khong phai tao thu muc khac chua id cua no
                        Int64 intstepSize = Convert.ToInt64(System.Configuration.ConfigurationManager.AppSettings["StepSizeForImage"].ToString());
                        Int64 stepFrom = Convert.ToInt64(Math.Round(Convert.ToDecimal(Convert.ToInt64(_strPatID) / intstepSize), 0)) * intstepSize;
                        Int64 stepTo = stepFrom + intstepSize - 1;
                        if (_dtSurgical.Rows.Count == 0)
                        {
                            MessageBox.Show("Bạn vui lòng nhập đầy đủ chữ viết tắt cho phẫu thuật", "Thông Báo");
                            return;
                        }
                        string strSymbol = cboLoaiPT_HA.Properties.GetDataSourceValue(InfoSurgical.SURSYMBOL, cboLoaiPT_HA.ItemIndex).ToString();
                        string strFilePath = strSymbol + System.IO.Path.DirectorySeparatorChar + stepFrom.ToString() + "-" + stepTo.ToString(); //can chinh lai o day 
                        dr[InfoClinicalPicture.CLPPICTURE] = strFilePath;
                        dr[InfoClinicalPicture.CLREXAMINATIONTIMES] = _intLanKham;
                        dr[InfoClinicalPicture.CLRREXAMINATIONTIMES] = _intLanTaiKham;
                        dr[InfoClinicalPicture.CLPPICNAME] = _strPatID + "-" + strSymbol + "_" + dr[InfoClinicalPicture.CLPISN].ToString() + "_" + strSuffix + Path.GetExtension(filename);
                        dr[InfoClinicalPicture.SURISN] = cboLoaiPT_HA.EditValue;
                        dr[InfoClinicalPicture.CLRISN] = _strCLRISN;
                        dr[InfoClinicalPicture.PATID] = _strPatID;
                        dr[InfoClinicalPicture.HIDDEN_IMAGE] = new Bitmap(filename);
                        dr[InfoClinicalPicture.HIDDEN_STATUS] = (int)InfoClinicalPicture.eHiddenStatus._Register;
                        dr[InfoClinicalPicture.HIDDEN_CHECK] = 0;
                        dr[InfoClinicalPicture.CLPPICDATE] = DateTime.Now;
                        dr[InfoClinicalPicture.HIDDEN_SURNAME] = strSymbol;
                        dt.Rows.Add(dr);
                    }
                }
            }
        }

        private void gvHinhAnh_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (cboLoaiPT_HA.ItemIndex == -1)
            {
                cboLoaiPT_HA.ItemIndex = 0;
            }
            if (gdHinhAnh.DataSource != null)
            {
                if (e.Column.Name == this.gcNo.Name)
                {
                    DataRow dr = gvHinhAnh.GetDataRow(gvHinhAnh.FocusedRowHandle);
                    if (dr == null)
                        return;

                    //kiem tra khong cho trung thu tu
                    DataTable dt = (DataTable)gdHinhAnh.DataSource;
                    if (dt.Select(InfoClinicalPicture.CLPNO + "=" + e.Value).Length > 1)
                    {
                        MessageBox.Show("Bạn vui lòng chọn lại số thứ tự khác của hình ảnh. Vì thứ tự này đã tồn tại", "Thông Báo", MessageBoxButtons.OK);
                        return;
                    }
                    //cap nhat lai luoi / ten cua image
                    dr[InfoClinicalPicture.CLPNO] = e.Value;
                    string strSURSymbol = string.Empty;
                    if (_dtSurgical.Select(InfoSurgical.SURISN + "=" + dr[InfoClinicalPicture.SURISN].ToString()).Length > 0)
                    {
                        strSURSymbol = _dtSurgical.Select(InfoSurgical.SURISN + "=" + dr[InfoClinicalPicture.SURISN].ToString())[0][InfoSurgical.SURSYMBOL].ToString();
                    }
                    string strPath = System.Configuration.ConfigurationManager.AppSettings["ServerImagePath"].ToString() + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICTURE].ToString() + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICNAME].ToString();
                    string strExtension = Path.GetExtension(strPath);
                    dr[InfoClinicalPicture.CLPPICNAME] = _strPatID + "-" + strSURSymbol + "_" + dr[InfoClinicalPicture.CLPNO].ToString() + "_" + strSuffix + strExtension;
                    if (dr[InfoClinicalPicture.HIDDEN_STATUS].ToString() != ((int)InfoClinicalPicture.eHiddenStatus._Register).ToString())
                        dr[InfoClinicalPicture.HIDDEN_STATUS] = (int)InfoClinicalPicture.eHiddenStatus._Updated;
                }
            }
        }

        private void gvHinhAnh_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (cboLoaiPT_HA.ItemIndex == -1)
            {
                cboLoaiPT_HA.ItemIndex = 0;
            }
            if (gdHinhAnh.DataSource != null)
            {
                DataRow drFocus = gvHinhAnh.GetDataRow(e.RowHandle);
                if (drFocus == null)
                {
                    return;
                }

                if (e.Column.Name == this.gcSelected.Name)
                {
                    drFocus[InfoClinicalPicture.HIDDEN_CHECK] = e.Value;
                    DataTable dt = (DataTable)gdHinhAnh.DataSource;
                    DataRow[] drChecked = dt.Select(InfoClinicalPicture.HIDDEN_CHECK + "=1");
                    if (drChecked.Length > 6)
                    {
                        drFocus[InfoClinicalPicture.HIDDEN_CHECK] = 0;
                        MessageBox.Show("Bạn không thể chọn trên 6 hình ảnh để so sánh", "Thông Báo");
                        return;
                    }

                    int i = 1;
                    foreach (DataRow dr in drChecked)
                    {
                        if (dr != null && dr[InfoClinicalPicture.HIDDEN_IMAGE] is Bitmap)
                        {
                            switch (i)
                            {
                                case 1:
                                    layPic1.Text = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    picZoom1.Image = (Bitmap)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                                    picZoom1.ToolTip = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    break;
                                case 2:
                                    if (picZoom1.Image != null)
                                    {
                                        layPic2.Text = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                        picZoom2.Image = (Bitmap)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                                        picZoom2.ToolTip = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    }
                                    break;
                                case 3:
                                    if (picZoom2.Image != null)
                                    {
                                        layPic3.Text = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                        picZoom3.Image = (Bitmap)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                                        picZoom3.ToolTip = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    }
                                    break;
                                case 4:
                                    if (picZoom1.Image != null)
                                    {
                                        layPic4.Text = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                        picZoom4.Image = (Bitmap)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                                        picZoom4.ToolTip = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    }
                                    break;
                                case 5:
                                    if (picZoom2.Image != null)
                                    {
                                        layPic5.Text = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                        picZoom5.Image = (Bitmap)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                                        picZoom5.ToolTip = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    }
                                    break;
                                case 6:
                                    if (picZoom4.Image != null)
                                    {
                                        layPic6.Text = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                        picZoom6.Image = (Bitmap)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                                        picZoom6.ToolTip = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                                    }
                                    break;
                            }
                        }
                        i++;
                    }
                    i = drChecked.Length;
                    while (i < 6)
                    {
                        switch (i)
                        {
                            case 0:
                                layPic1.Text = "Picture 1";
                                picZoom1.Image = null;
                                picZoom1.ToolTip = string.Empty;
                                break;
                            case 1:
                                layPic2.Text = "Picture 2";
                                picZoom2.Image = null;
                                picZoom2.ToolTip = string.Empty;
                                break;
                            case 2:
                                layPic3.Text = "Picture 3";
                                picZoom3.Image = null;
                                picZoom3.ToolTip = string.Empty;
                                break;
                            case 3:
                                layPic4.Text = "Picture 4";
                                picZoom4.Image = null;
                                picZoom4.ToolTip = string.Empty;
                                break;
                            case 4:
                                layPic5.Text = "Picture 5";
                                picZoom5.Image = null;
                                picZoom5.ToolTip = string.Empty;
                                break;
                            case 5:
                                layPic6.Text = "Picture 6";
                                picZoom6.Image = null;
                                picZoom6.ToolTip = string.Empty;
                                break;
                        }
                        i++;
                    }
                }
            }
        }

        private void btnLuuHinhAnh_Click(object sender, EventArgs e)
        {
            if (gdHinhAnh.DataSource != null)
            {
                TransactionManager trans = TransactionManager.ThreadTransactionMgr();
                try
                {
                    trans.BeginTransaction();
                    DataTable _dtHinhAnh = (DataTable)gdHinhAnh.DataSource;
                    _dtHinhAnh.AcceptChanges();
                    int isn = objController.GetNewCLRPIC(_strCLRISN);
                    foreach (DataRow dr in _dtHinhAnh.Rows)
                    {
                        // luu hinh anh vao thu muc rieng tren duong dan that
                        #region luu hinh anh vao thu muc rieng tren duong dan that
                        ///neu la edit hoac them moi thi moi luu
                        if (dr[InfoClinicalPicture.HIDDEN_STATUS].ToString() == ((int)InfoClinicalPicture.eHiddenStatus._Register).ToString() || dr[InfoClinicalPicture.HIDDEN_STATUS].ToString() == ((int)InfoClinicalPicture.eHiddenStatus._Updated).ToString())
                        {
                            //duong dan hien tai bao gom : ten thu muc : ten tắt của phẫu thuật + id theo thứ tự (có bước nhảy) ;
                            //ten file bao gom: thu tu của file, "_" + id cua benh nhan+ "-" + ten tat cua phau thuat
                            //nhung để hiển thị được dữ liệu cần phải vào dường dẫn này, đường dẫn trên server khi lưu file trên đường dẫn vật lý
                            //và khi load file phải cộng thêm vào đường dẫn local, phải copy file từ server về máy local khi load form (nếu chưa có file, nếu có rồi thì không copy)
                            string strFilePath = dr[InfoClinicalPicture.CLPPICTURE].ToString(); // không chưa tên file
                            strFilePath = System.Configuration.ConfigurationManager.AppSettings["ServerImagePath"].ToString() + System.IO.Path.DirectorySeparatorChar + strFilePath;
                            if (Directory.Exists(strFilePath) == false) //neu thu  muc khong ton tai
                            {
                                Directory.CreateDirectory(strFilePath);
                            }

                            string strFileName = strFilePath + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICNAME].ToString();
                            if (File.Exists(strFileName) == true)
                            {
                                File.Delete(strFileName);
                            }

                            Image imgTemp = (Image)dr[InfoClinicalPicture.HIDDEN_IMAGE];
                            imgTemp.Save(strFileName);

                            //tien hanh luu moi hoac cap nhat vao database
                            if (dr[InfoClinicalPicture.HIDDEN_STATUS].ToString() == ((int)InfoClinicalPicture.eHiddenStatus._Register).ToString())
                            {
                                dr[InfoClinicalPicture.CLPISN] = isn;
                                isn++;
                                objController.InsertRow(dr, new string[] { });
                            }
                            else
                            {
                                //neu la update, file xoa file cu,
                                string strOldFilePath = dr[InfoClinicalPicture.HIDDEN_PICPATH].ToString(); // không chưa tên file
                                strOldFilePath = System.Configuration.ConfigurationManager.AppSettings["ServerImagePath"].ToString() + System.IO.Path.DirectorySeparatorChar + strOldFilePath;
                                string strOldFileName = strOldFilePath + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.HIDDEN_PICNAME].ToString();
                                if (File.Exists(strOldFileName) == true)
                                {
                                    File.Delete(strOldFileName);
                                }

                                ListDictionary updateField = new ListDictionary();
                                updateField.Add(InfoClinicalPicture.SURISN, dr[InfoClinicalPicture.SURISN]);
                                updateField.Add(InfoClinicalPicture.CLPPICNAME, dr[InfoClinicalPicture.CLPPICNAME]);
                                updateField.Add(InfoClinicalPicture.CLPPICTURE, dr[InfoClinicalPicture.CLPPICTURE]);
                                updateField.Add(InfoClinicalPicture.CLPNO, dr[InfoClinicalPicture.CLPNO]);

                                List<ExpressionObject> param = new List<ExpressionObject>();
                                param.Add(new ExpressionObject(InfoClinicalPicture.CLPISN, dr[InfoClinicalPicture.CLPISN]));
                                objController.UpdateRow(InfoClinicalPicture.TABLENAME, updateField, param);
                            }

                            dr[InfoClinicalPicture.HIDDEN_STATUS] = (int)InfoClinicalPicture.eHiddenStatus._HaveValue;
                            dr[InfoClinicalPicture.HIDDEN_PICPATH] = dr[InfoClinicalPicture.CLPPICTURE];
                            dr[InfoClinicalPicture.HIDDEN_PICNAME] = dr[InfoClinicalPicture.CLPPICNAME];
                        }
                        #endregion
                    }

                    trans.CommitTransaction();
                    MessageBox.Show("Đã cập nhật hình ảnh thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    trans.RollbackTransaction();
                    Class.ShowException(ex);
                }

            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gdHinhAnh.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gdHinhAnh.DataSource;
            if (dt.Select(InfoClinicalPicture.HIDDEN_CHECK + "=1").Length == 0)
            {
                MessageBox.Show("Vui lòng check vào 1 dòng trong danh sách", "Thông Báo");
                return;
            }

            TransactionManager trans = TransactionManager.ThreadTransactionMgr();
            try
            {
                trans.BeginTransaction();

                foreach (DataRow dr in dt.Select(InfoClinicalPicture.HIDDEN_CHECK + "=1"))
                {
                    dr[InfoClinicalPicture.HIDDEN_STATUS] = (int)InfoClinicalPicture.eHiddenStatus._Deleted;
                    dr[InfoClinicalPicture.HIDDEN_IMAGE] = null;

                    string strImageName = dr[InfoClinicalPicture.CLPPICNAME].ToString();
                    ///phai xoa image dang duoc hien thi ben vung ben phai ///TO DO
                    #region Clear image vung ben phai
                    if (picZoom1.ToolTip.Equals(strImageName))
                    {
                        picZoom1.Image = null;
                        picZoom1.ToolTip = string.Empty;
                        layPic1.HideToCustomization();
                    }
                    if (picZoom2.ToolTip.Equals(strImageName))
                    {
                        picZoom2.Image = null;
                        picZoom2.ToolTip = string.Empty;
                        layPic2.HideToCustomization();
                    }
                    if (picZoom3.ToolTip.Equals(strImageName))
                    {
                        picZoom3.Image = null;
                        picZoom3.ToolTip = string.Empty;
                        layPic3.HideToCustomization();
                    }
                    if (picZoom4.ToolTip.Equals(strImageName))
                    {
                        picZoom4.Image = null;
                        picZoom4.ToolTip = string.Empty;
                        layPic4.HideToCustomization();
                    }
                    if (picZoom5.ToolTip.Equals(strImageName))
                    {
                        picZoom5.Image = null;
                        picZoom5.ToolTip = string.Empty;
                        layPic5.HideToCustomization();
                    }
                    if (picZoom6.ToolTip.Equals(strImageName))
                    {
                        picZoom6.Image = null;
                        picZoom6.ToolTip = string.Empty;
                        layPic6.HideToCustomization();
                    }
                    #endregion
                    string strFilePath = dr[InfoClinicalPicture.CLPPICTURE].ToString(); // không chưa tên file
                    strFilePath = System.Configuration.ConfigurationManager.AppSettings["ServerImagePath"].ToString() + System.IO.Path.DirectorySeparatorChar + strFilePath;
                    string strFileName = strFilePath + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICNAME].ToString();
                    if (File.Exists(strFileName) == true)
                    {
                        File.Delete(strFileName);
                    }

                    //xoa record
                    objController.DeleteRow(dr, new string[] { InfoClinicalPicture.CLPISN,InfoClinicalPicture.CLRISN });

                    dr.Delete();
                }
                trans.CommitTransaction();
            }
            catch (Exception ex)
            {
                trans.RollbackTransaction();
                Class.ShowException(ex);
            }
            //neu xoa het image thi isn reset ve bang 1
            if (dt.Rows.Count == 0)
                isn = 1;
        }

        /// <summary>
        /// cap nhat loai phau thuat
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCapNhatLoaiPT_Click(object sender, EventArgs e)
        {
            if (gdHinhAnh.DataSource == null)
            {
                return;
            }
            if (cboLoaiPT_HA.ItemIndex == -1)
            {
                cboLoaiPT_HA.ItemIndex = 0;
            }

            DataTable dt = (DataTable)gdHinhAnh.DataSource;
            if (dt.Select(InfoClinicalPicture.HIDDEN_CHECK + "=1").Length == 0)
            {
                MessageBox.Show("Vui lòng check vào 1 dòng trong danh sách", "Thông Báo");
                return;
            }
            int intUpdate = 0;
            try
            {
                foreach (DataRow dr in dt.Select(InfoClinicalPicture.HIDDEN_CHECK + "=1"))
                {
                    if (dr[InfoClinicalPicture.CLREXAMINATIONTIMES].ToString().Equals(_intLanKham.ToString()) && dr[InfoClinicalPicture.CLRREXAMINATIONTIMES].ToString().Equals(_intLanTaiKham.ToString()))
                    {
                        if (dr[InfoClinicalPicture.SURISN].ToString().Equals(cboLoaiPT_HA.EditValue.ToString()))
                        {
                            dr[InfoClinicalPicture.HIDDEN_CHECK] = "0";
                            intUpdate++;
                            continue;
                        }

                        #region luu lại hình cũ, trước khi cập nhật thông tin cho hình mới
                        dr[InfoClinicalPicture.HIDDEN_PICPATH] = dr[InfoClinicalPicture.CLPPICTURE];
                        dr[InfoClinicalPicture.HIDDEN_PICNAME] = dr[InfoClinicalPicture.CLPPICNAME];
                        #endregion

                        string strSURSymbol = string.Empty;
                        strSURSymbol = cboLoaiPT_HA.Properties.GetDataSourceValue(InfoSurgical.SURSYMBOL, cboLoaiPT_HA.ItemIndex).ToString();

                        string strPath = System.Configuration.ConfigurationManager.AppSettings["ServerImagePath"].ToString() + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICTURE].ToString() + System.IO.Path.DirectorySeparatorChar + dr[InfoClinicalPicture.CLPPICNAME].ToString();
                        string strExtension = Path.GetExtension(strPath);

                        //cap nhat lai ten cua image/ ten duong dan
                        Int64 intstepSize = Convert.ToInt64(System.Configuration.ConfigurationManager.AppSettings["StepSizeForImage"].ToString());
                        Int64 stepFrom = Convert.ToInt64(Math.Round(Convert.ToDecimal(Convert.ToInt64(_strPatID) / intstepSize), 0)) * intstepSize;
                        Int64 stepTo = stepFrom + intstepSize - 1;
                        string strFilePath = strSURSymbol + System.IO.Path.DirectorySeparatorChar + stepFrom.ToString() + "-" + stepTo.ToString(); //can chinh lai o day 
                        dr[InfoClinicalPicture.CLPPICTURE] = strFilePath;
                        dr[InfoClinicalPicture.CLPPICNAME] = _strPatID + "-" + strSURSymbol + "_" + dr[InfoClinicalPicture.CLPNO].ToString() + "_" + strSuffix + strExtension;
                        if (dr[InfoClinicalPicture.HIDDEN_STATUS].ToString() != ((int)InfoClinicalPicture.eHiddenStatus._Register).ToString())
                            dr[InfoClinicalPicture.HIDDEN_STATUS] = (int)InfoClinicalPicture.eHiddenStatus._Updated;
                        dr[InfoClinicalPicture.SURISN] = cboLoaiPT_HA.EditValue.ToString();
                        dr[InfoClinicalPicture.HIDDEN_SURNAME] = strSURSymbol;
                        intUpdate++;
                    }
                    dr[InfoClinicalPicture.HIDDEN_CHECK] = "0";
                }

            }
            catch (Exception ex)
            {
                Class.ShowException(ex);
            }
            if (intUpdate == 0)
            {
                MessageBox.Show("Bạn chỉ có thể cập nhật thông tin cho lần khám và lần tái khám mà bạn đã chọn từ bên Hồ Sơ Bệnh Án", "Thông Báo");
            }
            else
                btnLuuHinhAnh_Click(sender, e);
        }

        #endregion

        #region Chi Tiet Phau Thuat
        private void cboLoaiPhauThuat_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl.SelectedTabPage == tabThongTinChiTiet)
            {
                if (_dtSurgical.Rows.Count == 0)
                {
                    MessageBox.Show("Bạn vui lòng nhập đầy đủ chữ viết tắt cho phẫu thuật", "Thông Báo");
                    return;
                }
                this.ucChiTietPhauThuat.PatientID = this._strPATISN;
                string surISN = cboLoaiPhauThuat.SelectedValue.ToString();
                this.ucChiTietPhauThuat.SurgicalID = surISN;
                this.ucChiTietPhauThuat.ExtraID1 = this._strCLRISN;
                this.ucChiTietPhauThuat.getData();
            }
        }
        #endregion


    }
}